import { ApiService } from './ApiService'
import { StorageUtil } from '../utils/StorageUtil'
import { Constants } from '../utils/Constants'

/**
 * 用户服务类
 */
export class UserService {
  private static instance: UserService
  private apiService: ApiService
  private storageUtil: StorageUtil

  private constructor() {
    this.apiService = ApiService.getInstance()
    this.storageUtil = StorageUtil.getInstance()
  }

  /**
   * 获取单例实例
   */
  static getInstance(): UserService {
    if (!this.instance) {
      this.instance = new UserService()
    }
    return this.instance
  }

  /**
   * 用户登录
   */
  async login(phoneNumber: string, password: string, userType: string): Promise<any> {
    try {
      const response = await this.apiService.login({
        phoneNumber,
        password,
        userType
      })

      if (response.success) {
        // 保存用户信息到本地存储
        await this.storageUtil.saveUserInfo(response.data.user)
        await this.storageUtil.saveToken(response.data.token)
        await this.storageUtil.saveUserType(userType)
        
        // 设置API服务的token
        this.apiService.setToken(response.data.token)
      }

      return response
    } catch (error) {
      console.error('用户登录失败:', error)
      throw error
    }
  }

  /**
   * 用户注册
   */
  async register(userData: {
    phoneNumber: string
    password: string
    userType: string
    name: string
    email?: string
    address?: string
  }): Promise<any> {
    try {
      const response = await this.apiService.register(userData)

      if (response.success) {
        // 保存用户信息到本地存储
        await this.storageUtil.saveUserInfo(response.data.user)
        await this.storageUtil.saveToken(response.data.token)
        await this.storageUtil.saveUserType(userData.userType)
        
        // 设置API服务的token
        this.apiService.setToken(response.data.token)
      }

      return response
    } catch (error) {
      console.error('用户注册失败:', error)
      throw error
    }
  }

  /**
   * 获取当前用户信息
   */
  async getCurrentUser(): Promise<any> {
    try {
      const userInfo = await this.storageUtil.getUserInfo()
      return userInfo
    } catch (error) {
      console.error('获取当前用户信息失败:', error)
      return null
    }
  }

  /**
   * 获取当前用户类型
   */
  async getCurrentUserType(): Promise<string> {
    try {
      const userType = await this.storageUtil.getUserType()
      return userType
    } catch (error) {
      console.error('获取当前用户类型失败:', error)
      return ''
    }
  }

  /**
   * 更新用户信息
   */
  async updateUserInfo(userData: any): Promise<any> {
    try {
      const currentUser = await this.getCurrentUser()
      if (!currentUser) {
        throw new Error('用户未登录')
      }

      const response = await this.apiService.updateUserInfo(currentUser.id, userData)

      if (response.success) {
        // 更新本地存储的用户信息
        await this.storageUtil.saveUserInfo(response.data)
      }

      return response
    } catch (error) {
      console.error('更新用户信息失败:', error)
      throw error
    }
  }

  /**
   * 修改密码
   */
  async changePassword(oldPassword: string, newPassword: string): Promise<any> {
    try {
      const currentUser = await this.getCurrentUser()
      if (!currentUser) {
        throw new Error('用户未登录')
      }

      return await this.apiService.changePassword({
        userId: currentUser.id,
        oldPassword,
        newPassword
      })
    } catch (error) {
      console.error('修改密码失败:', error)
      throw error
    }
  }

  /**
   * 退出登录
   */
  async logout(): Promise<void> {
    try {
      // 清除本地存储的用户信息
      await this.storageUtil.removeUserInfo()
      await this.storageUtil.removeToken()
      await this.storageUtil.removeUserType()
      await this.storageUtil.clearCartData()
      
      // 清除API服务的token
      this.apiService.setToken('')
    } catch (error) {
      console.error('退出登录失败:', error)
      throw error
    }
  }

  /**
   * 检查是否登录
   */
  async isLoggedIn(): Promise<boolean> {
    try {
      const token = await this.storageUtil.getToken()
      const userInfo = await this.storageUtil.getUserInfo()
      
      if (token && userInfo) {
        // 设置API服务的token
        this.apiService.setToken(token)
        return true
      }
      
      return false
    } catch (error) {
      console.error('检查登录状态失败:', error)
      return false
    }
  }

  /**
   * 获取用户地址列表
   */
  async getUserAddresses(): Promise<any[]> {
    try {
      const currentUser = await this.getCurrentUser()
      if (!currentUser) {
        throw new Error('用户未登录')
      }

      return await this.apiService.getUserAddresses(currentUser.id)
    } catch (error) {
      console.error('获取用户地址失败:', error)
      throw error
    }
  }

  /**
   * 添加用户地址
   */
  async addUserAddress(addressData: {
    name: string
    phoneNumber: string
    address: string
    isDefault?: boolean
  }): Promise<any> {
    try {
      const currentUser = await this.getCurrentUser()
      if (!currentUser) {
        throw new Error('用户未登录')
      }

      const response = await this.apiService.addUserAddress({
        userId: currentUser.id,
        ...addressData
      })

      return response
    } catch (error) {
      console.error('添加用户地址失败:', error)
      throw error
    }
  }

  /**
   * 更新用户地址
   */
  async updateUserAddress(addressId: string, addressData: any): Promise<any> {
    try {
      return await this.apiService.updateUserAddress(addressId, addressData)
    } catch (error) {
      console.error('更新用户地址失败:', error)
      throw error
    }
  }

  /**
   * 删除用户地址
   */
  async deleteUserAddress(addressId: string): Promise<any> {
    try {
      return await this.apiService.deleteUserAddress(addressId)
    } catch (error) {
      console.error('删除用户地址失败:', error)
      throw error
    }
  }

  /**
   * 设置默认地址
   */
  async setDefaultAddress(addressId: string): Promise<any> {
    try {
      const currentUser = await this.getCurrentUser()
      if (!currentUser) {
        throw new Error('用户未登录')
      }

      return await this.apiService.setDefaultAddress(currentUser.id, addressId)
    } catch (error) {
      console.error('设置默认地址失败:', error)
      throw error
    }
  }

  /**
   * 获取默认地址
   */
  async getDefaultAddress(): Promise<any> {
    try {
      const currentUser = await this.getCurrentUser()
      if (!currentUser) {
        throw new Error('用户未登录')
      }

      const addresses = await this.getUserAddresses()
      return addresses.find(addr => addr.isDefault) || addresses[0] || null
    } catch (error) {
      console.error('获取默认地址失败:', error)
      return null
    }
  }

  /**
   * 验证手机号格式
   */
  validatePhoneNumber(phoneNumber: string): boolean {
    const phoneRegex = /^1[3-9]\d{9}$/
    return phoneRegex.test(phoneNumber)
  }

  /**
   * 验证密码格式
   */
  validatePassword(password: string): boolean {
    return password.length >= 6 && password.length <= 20
  }

  /**
   * 验证邮箱格式
   */
  validateEmail(email: string): boolean {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    return emailRegex.test(email)
  }
}